package main

import (
	"fmt"
	"io"
	"net"
)

func main() {
	bindAndListen()
}

// 绑定并监听
func bindAndListen() {
	listen, err := net.Listen("tcp4", "127.0.0.1:12511")
	if err != nil {
		fmt.Println(err)
	}

	defer func(listen net.Listener) {
		err := listen.Close()
		if err != nil {
			fmt.Println(err)
		}
	}(listen)

	for {
		conn, err := listen.Accept()
		if err != nil {
			fmt.Println(err)
		}

		go handleConn(conn)
	}
}

// 处理连接
func handleConn(conn net.Conn) {
	defer conn.Close()
	buf := make([]byte, 1024)
	for {
		n, err := conn.Read(buf)
		if err != nil {
			if err == io.EOF {
				fmt.Println("connection closed by remote", conn.RemoteAddr())
				break
			}
			fmt.Println(err)
			break
		}
		_, err = conn.Write(buf[:n])
		if err != nil {
			fmt.Println("failed to write to remote", conn.RemoteAddr(), err)
			break
		}
	}
}
